package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

public class JthyshNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={
		
		"http://.*.jthysh.com/.*/[0-9]{8}/[0-9]*.html",
		"http://.*.jthysh.com/index.php\\?a=show&c=index&catid=[0-9]*&id=[0-9]*&m=content",
		"http://.*.jthysh.com/.*[0-9]{4}/[0-9]{4}/[0-9]*.html",
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("h1.view-tit").text();	
		if (title!=null)title=StringUtils.substringBefore(title, "_");
		content=HtmlCleaner.getContentHtml(url,doc.select("div.view-main"));
		date=DateUtils.matchDate(doc.select("p.sub-view-tit").text());
		
		if (StringUtils.isNotBlank(title) && date!=null){			
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setDate(date);	
		}
		return news;
	}	
	
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
	
	public static void main(String[] args) {
		String url="http://jx.jthysh.com/news/jiuzhenzhinan/nanchangyibao/2013/0808/31.html";
		JthyshNewsAnalyse analyse=new JthyshNewsAnalyse();		
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	

}
